﻿using HDLogCenter.Dal.Repos;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Utils;
using HDLogCenter.Infrastructure.Services;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HDLogCenter.Infrastructure.ExternalServices
{
    public class LogMQMessageHandlerService
    {
        private readonly RabbitMQService _rabbitMQService;
        private readonly MeiliSearchService _meiliSearchService;
        private readonly ILogger<LogMQMessageHandlerService> _logger;

        public LogMQMessageHandlerService(
            RabbitMQService rabbitMQService,
            MeiliSearchService meiliSearchService,
            ILogger<LogMQMessageHandlerService> logger)
        {
            _rabbitMQService = rabbitMQService;
            _meiliSearchService = meiliSearchService;
            _logger = logger;
        }

        public async Task<bool> LogHandlerAsync()
        {
            try
            {
                var logs = _rabbitMQService.PullLogMessageFromQueue();

                if (logs == null || logs.Count == 0)
                {
                    return true;
                }

                var logDtos = new List<LogDto>();
                foreach (var item in logs)
                {
                    var logDto = new LogDto
                    {
                        Id = SnowflakeIdGenerator.NextId(),
                        Code = item.Code,
                        CreateTime = item.CreateTime.ToUnixTime(),
                        ErrorStack = item.ErrorStack,
                        HttpMethod = item.HttpMethod,
                        Level = item.Level,
                        IsTimeout = item.IsTimeout,
                        Message = item.Message,
                        Millisecond = item.Millisecond,
                        ServerCode = item.ServerCode,
                        ServerIP = item.ServerIp,
                        URL = item.Url
                    };

                    logDtos.Add(logDto);

                    // 检查是否需要触发报警
                    // await _alertRuleMonitorService.HandleLogAsync(logDto);
                }

                // 批量插入日志到搜索引擎
                var insertResult = await _meiliSearchService.BatchInsertLogsAsync(logDtos);

                if (!insertResult)
                { 
                    _logger.LogError("批量插入日志失败");
                }

                return insertResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理日志消息时发生错误: {ErrorMessage}", ex.Message);
                return false;
            }
        }

    }
}
